{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "a517affc-fdef-4627-b1f5-5c4754f44c14",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "import os\n",
    "import numpy as np\n",
    "\n",
    "in_path = '/home/ljw22/workspace/qwen/MUSER-main/cases_pool.json'\n",
    "\n",
    "in_file = open(in_path, 'r', encoding='utf-8')\n",
    "cases_pool = json.load(in_file)\n",
    "\n",
    "# 训练集和数据集合并，因为不需要进行训练，全部进行测试\n",
    "train_test_path = '/home/ljw22/workspace/qwen/MUSER-main/data/cases/train_test.json'\n",
    "train_test_file = open(train_test_path, 'r')\n",
    "train_test = json.load(train_test_file)\n",
    "test_querys = train_test['train'] + train_test['test']  #\n",
    "\n",
    "\n",
    "qc_pairs_path = '/home/ljw22/workspace/qwen/MUSER-main/data/cases/cands_by_query.json'\n",
    "qc_pairs_file = open(qc_pairs_path, 'r')\n",
    "qc_pairs = json.load(qc_pairs_file)\n",
    "\n",
    "feature_path = \"/home/ljw22/workspace/qwen/MUSER-main/data/features/14B_feature.json\"\n",
    "\n",
    "with open(feature_path) as fin:\n",
    "    feature = json.load(fin)\n",
    "\n",
    "docid_list = list(feature.keys())\n",
    "\n",
    "docid_id_dict = {}\n",
    "\n",
    "for id, docid in enumerate(docid_list):\n",
    "    docid_id_dict[docid] = id\n",
    "\n",
    "\n",
    "feature_matric = []\n",
    "for doc in docid_list:\n",
    "    feature_matric.append(feature[doc])  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "8b036d94-2f75-4137-9d91-abca251b5c63",
   "metadata": {},
   "outputs": [],
   "source": [
    "docid_id_dict = {}\n",
    "for i, docid in enumerate(docid_list):\n",
    "    docid_id_dict[docid] = i"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "d062d48a-8c61-41c4-8bd7-9122ae94db1c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "计算余弦相似度\n",
      "(4024, 4024)\n"
     ]
    }
   ],
   "source": [
    "A = np.array(feature_matric)\n",
    "\n",
    "print(\"计算余弦相似度\")\n",
    "# 计算每一行的 L2 范数（每个特征的长度）\n",
    "norms = np.linalg.norm(A, axis=1, keepdims=True)\n",
    "\n",
    "# 计算余弦相似度矩阵\n",
    "norms[norms == 0] = 1  # 可以把零范数的行设为1，防止除以0\n",
    "\n",
    "# 计算余弦相似度矩阵\n",
    "similarity_matrix = np.dot(A, A.T) / (norms * norms.T)\n",
    "\n",
    "print(similarity_matrix.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "739efd0e-e442-4e6e-83bc-fea69b68847f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 所有候选分词之后的结果，用于进行相似度计算\n",
    "corpus_path = '/home/ljw22/workspace/qwen/MUSER-main/data/cases/corpus.json'\n",
    "corpus_file = open(corpus_path, 'r', encoding='utf-8')\n",
    "corpus = json.load(corpus_file)\n",
    "\n",
    "# 停词集合\n",
    "stopword_path = '/home/ljw22/workspace/qwen/MUSER-main/data/utils/stopword.txt'\n",
    "stopword_file = open(stopword_path, 'r', encoding='utf-8')\n",
    "lines = stopword_file.readlines()\n",
    "stopwords = [i.strip() for i in lines]\n",
    "stopwords.extend(['.','（','）','-', '', '【', '】'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c63032e8-c97d-408d-ac0a-bbac5166917f",
   "metadata": {},
   "outputs": [],
   "source": [
    "import jieba\n",
    "from tqdm import tqdm\n",
    "from gensim.summarization import bm25"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "ec4b659b-b838-42f8-a605-fcdc7a165cf8",
   "metadata": {},
   "outputs": [],
   "source": [
    "bm25Model = bm25.BM25(corpus)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "296044a4-ba93-4914-84b7-1d54a093910b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.5\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 100/100 [01:14<00:00,  1.35it/s]\n"
     ]
    }
   ],
   "source": [
    "bm25_top100 = {}\n",
    "alpha_list = [0.5]\n",
    "for alpha in alpha_list:\n",
    "    print(alpha)\n",
    "    for qid in tqdm(test_querys):\n",
    "        array_idx = docid_id_dict[qid]\n",
    "        sim_scores = []\n",
    "        query_text = ''\n",
    "        for part in ['本院查明']:\n",
    "            for sent in cases_pool[qid]['content'][part]:\n",
    "                query_text += sent\n",
    "        query_jieba = jieba.cut(query_text, cut_all=False)\n",
    "        query_tmp = ' '.join(query_jieba).split()\n",
    "        query_cutted = [w for w in query_tmp if w not in stopwords]\n",
    "        sim_ndarray = np.array(bm25Model.get_scores(query_cutted))\n",
    "        sim = (sim_ndarray / sim_ndarray.max()).tolist()\n",
    "        # print(sim)\n",
    "        # print(len(sim))\n",
    "        # break\n",
    "        for idx, score in zip(cases_pool.keys(), sim):\n",
    "            cand_idx = docid_id_dict[idx]\n",
    "            i = int(idx)\n",
    "            if qid == i or i not in qc_pairs[qid]:\n",
    "            # if int(qid) == i:\n",
    "                continue\n",
    "            mscore = alpha * score + (1 - alpha) * similarity_matrix[array_idx][cand_idx]\n",
    "            sim_scores.append((idx, mscore))\n",
    "        # assert len(sim_scores) == 100\n",
    "        sim_scores.sort(key=lambda x:x[1], reverse=True)\n",
    "        # print(sim_scores)\n",
    "        cnt = 0\n",
    "        bm25_top100[qid] = []\n",
    "        for idx, score in sim_scores:\n",
    "            if cnt >= 100:\n",
    "                break\n",
    "            bm25_top100[qid].append(idx)\n",
    "            cnt += 1\n",
    "        assert len(bm25_top100[qid]) == 100\n",
    "    \n",
    "    out_path = f'/home/ljw22/workspace/qwen/MUSER-main/data/my_predictions/bm25_pre/alpha-{alpha}.json'\n",
    "    out_file = open(out_path, 'w')\n",
    "    json.dump(bm25_top100, out_file)\n",
    "    out_file.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e1d8328a-62a4-4482-a78e-c5b1a96937e5",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.20"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
